<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF页面信息统计工具</title>
    <!-- 本地引用Tailwind CSS -->
    <script src="../../assets/js/tailwind.min.js"></script>
    <!-- 本地引用pdf-lib.min.js，FileSaver.min.js -->
    <script src="../../assets/js/pdf-lib.min.js"></script>
    <script src="../../assets/js/FileSaver.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#64748b',
                        accent: '#0ea5e9',
                        neutral: '#f1f5f9',
                        success: '#10b981',
                        warning: '#f59e0b',
                        danger: '#ef4444',
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .transition-height {
                transition: max-height 0.5s ease;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .animate-fadeIn {
                animation: fadeIn 0.5s ease-in-out;
            }
            @keyframes fadeIn {
                0% { opacity: 0; transform: translateY(20px); }
                100% { opacity: 1; transform: translateY(0); }
            }
        }
    </style>
</head>
<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-md sticky top-0 z-50 transition-all duration-300">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <span class="text-primary text-2xl">📅</span>
                <h1 class="text-xl md:text-2xl font-bold text-gray-800">PDF页面信息统计工具</h1>
            </div>
            <div class="flex items-center space-x-4">
                <button id="themeToggle" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <span class="text-gray-600">🌙</span>
                </button>
                <button id="helpBtn" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <span class="text-gray-600">❓</span>
                </button>
            </div>
        </div>
    </header>

    <!-- 主要内容区 -->
    <main class="flex-grow container mx-auto px-4 py-8">
        <!-- 文件上传区 -->
        <section id="uploadSection" class="mb-8">
            <div class="bg-white rounded-xl shadow-lg p-6 transition-all duration-300 hover:shadow-xl">
                <div class="text-center mb-6">
                    <h2 class="text-2xl font-bold text-gray-800 mb-2">上传PDF文件</h2>
                    <p class="text-gray-600">选择一个PDF文件来分析其页面信息</p>
                </div>
                
                <div id="dropZone" class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center cursor-pointer hover:border-primary transition-colors">
                    <span class="text-5xl text-gray-400 mb-4">☁️</span>
                    <p class="text-gray-600 mb-2">拖放PDF文件到这里，或</p>
                    <label class="relative">
                        <span class="inline-block bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-all duration-300 transform hover:scale-105 shadow-md hover:shadow-lg">
                            选择文件
                        </span>
                        <input type="file" id="fileInput" accept=".pdf" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer">
                    </label>
                </div>
                
                <div id="fileInfo" class="mt-4 hidden">
                    <div class="flex items-center justify-between bg-gray-50 p-3 rounded-lg">
                        <div class="flex items-center space-x-3">
                            <span class="text-primary text-xl">📄</span>
                            <div>
                                <p id="fileName" class="font-medium text-gray-800 truncate max-w-md"></p>
                                <p id="fileSize" class="text-sm text-gray-500"></p>
                            </div>
                        </div>
                        <button id="removeFile" class="text-gray-400 hover:text-danger transition-colors">
                            <span>❌</span>
                        </button>
                    </div>
                    <div class="mt-4 text-center">
                        <button id="analyzeBtn" class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-all duration-300 transform hover:scale-105 shadow-md hover:shadow-lg flex items-center mx-auto">
                            <span class="mr-2">📊</span>开始分析
                        </button>
                    </div>
                </div>
            </div>
        </section>

        <!-- 统计结果区 -->
        <section id="resultSection" class="mb-8 hidden">
            <div class="bg-white rounded-xl shadow-lg p-6 transition-all duration-300 hover:shadow-xl">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold text-gray-800">页面统计结果</h2>
                    <div class="flex space-x-2">
                        <button id="exportCSV" class="bg-success hover:bg-success/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 flex items-center">
                            <span class="mr-2">📊</span>导出CSV
                        </button>
                        <button id="splitPDF" class="bg-accent hover:bg-accent/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 flex items-center">
                            <span class="mr-2">✂️</span>按尺寸拆分
                        </button>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                    <div class="bg-gray-50 rounded-lg p-4 shadow-sm">
                        <div class="flex items-center justify-between mb-2">
                            <h3 class="font-semibold text-gray-700">总页数</h3>
                            <span class="text-primary text-xl">📄</span>
                        </div>
                        <p id="totalPages" class="text-3xl font-bold text-gray-800">0</p>
                    </div>
                    
                    <div class="bg-gray-50 rounded-lg p-4 shadow-sm">
                        <div class="flex items-center justify-between mb-2">
                            <h3 class="font-semibold text-gray-700">页面尺寸种类</h3>
                            <span class="text-accent text-xl">📏</span>
                        </div>
                        <p id="sizeTypes" class="text-3xl font-bold text-gray-800">0</p>
                    </div>
                    
                    <div class="bg-gray-50 rounded-lg p-4 shadow-sm">
                        <div class="flex items-center justify-between mb-2">
                            <h3 class="font-semibold text-gray-700">处理时间</h3>
                            <span class="text-warning text-xl">⏱️</span>
                        </div>
                        <p id="processingTime" class="text-3xl font-bold text-gray-800">0s</p>
                    </div>
                </div>
                
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">页面尺寸</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">页数</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">占比</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">页码范围</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                            </tr>
                        </thead>
                        <tbody id="sizeStatsTable" class="bg-white divide-y divide-gray-200">
                            <!-- 表格内容将通过JS动态生成 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </section>

        <!-- 拆分PDF模态框 -->
        <div id="splitModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
            <div class="bg-white rounded-xl shadow-2xl p-6 w-full max-w-md mx-4 transform transition-all duration-300 scale-95 opacity-0" id="modalContent">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-xl font-bold text-gray-800">按尺寸拆分PDF</h3>
                    <button id="closeModal" class="text-gray-400 hover:text-gray-600">
                        <span>❌</span>
                    </button>
                </div>
                
                <div class="mb-4">
                    <label for="splitRanges" class="block text-sm font-medium text-gray-700 mb-2">页码范围</label>
                    <input type="text" id="splitRanges" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors" placeholder="例如: 1-5,7,9-12">
                    <p class="mt-1 text-sm text-gray-500">多个范围用逗号分隔</p>
                </div>
                
                <div class="flex justify-end space-x-3">
                    <button id="cancelSplit" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">
                        取消
                    </button>
                    <button id="confirmSplit" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                        确认拆分
                    </button>
                </div>
            </div>
        </div>

        <!-- 加载动画 -->
        <div id="loadingOverlay" class="fixed inset-0 bg-white bg-opacity-80 z-50 flex items-center justify-center hidden">
            <div class="flex flex-col items-center">
                <div class="w-16 h-16 border-4 border-primary border-t-transparent rounded-full animate-spin mb-4"></div>
                <p class="text-gray-700 font-medium" id="loadingText">处理中...</p>
            </div>
        </div>
    </main>

    <script>
        // 定义常见页面尺寸（单位：毫米）
        const commonSizes = {
            A0: { width: 841, height: 1189 },
            A1: { width: 594, height: 841 },
            A2: { width: 420, height: 594 },
            A3: { width: 297, height: 420 },
            A4: { width: 210, height: 297 },
            A5: { width: 148, height: 210 },
            A6: { width: 105, height: 148 },
            Letter: { width: 215.9, height: 279.4 },
            Legal: { width: 215.9, height: 355.6 },
        };

        // 将毫米转换为点（1毫米 = 2.83464567点）
        function mmToPoints(mm) {
            return mm * 2.83464567;
        }

        // 检查尺寸是否接近某个常见尺寸
        function isCloseToSize(width, height, size, tolerance = 2) {
            const diffWidth = Math.abs(width - mmToPoints(size.width));
            const diffHeight = Math.abs(height - mmToPoints(size.height));
            return diffWidth <= mmToPoints(tolerance) && diffHeight <= mmToPoints(tolerance);
        }

        // 获取页面尺寸类型
        function getPageSizeType(width, height) {
            // 检查是否为常见尺寸，不区分方向
            for (const [sizeName, size] of Object.entries(commonSizes)) {
                if (isCloseToSize(width, height, size) || isCloseToSize(height, width, size)) {
                    return sizeName;
                }
            }
            // 如果不是常见尺寸，返回具体尺寸（毫米单位）
            const mmWidth = (width / 2.83464567).toFixed(2);
            const mmHeight = (height / 2.83464567).toFixed(2);
            return `${Math.min(mmWidth, mmHeight)} x ${Math.max(mmWidth, mmHeight)} mm`;
        }

        // 定义一个函数，将页面编号数组转换为更符合人类习惯的描述
        function miaoshu(pages) {
            if (pages.length === 0) {
                return '';
            }
            if (pages.length === 1) {
                return `${pages[0]}`;
            }
            pages.sort((a, b) => a - b);
            const ranges = [];
            let start = pages[0];
            let end = pages[0];
            for (let i = 1; i < pages.length; i++) {
                if (pages[i] === end + 1) {
                    end = pages[i];
                } else {
                    if (start === end) {
                        ranges.push(`${start}`);
                    } else {
                        ranges.push(`${start}-${end}`);
                    }
                    start = pages[i];
                    end = pages[i];
                }
            }
            if (start === end) {
                ranges.push(`${start}`);
            } else {
                ranges.push(`${start}-${end}`);
            }
            return ranges.join('，');
        }

        // 解析页码范围字符串，支持多种语言环境
        function parsePageRanges(pageRangeStr) {
            const ranges = [];
            const parts = pageRangeStr.split(',').map(part => part.trim());

            for (const part of parts) {
                if (part.includes('-')) {
                    const [start, end] = part.split('-').map(Number);
                    ranges.push({ start, end });
                } else {
                    const page = Number(part);
                    ranges.push({ start: page, end: page });
                }
            }

            return ranges;
        }

        // 全局变量存储当前处理的文件和统计结果
        let currentFile = null;
        let pdfStats = null;
        let pdfLibReady = false;

        // DOM元素
        const dropZone = document.getElementById('dropZone');
        const fileInput = document.getElementById('fileInput');
        const fileInfo = document.getElementById('fileInfo');
        const fileName = document.getElementById('fileName');
        const fileSize = document.getElementById('fileSize');
        const removeFile = document.getElementById('removeFile');
        const resultSection = document.getElementById('resultSection');
        const totalPages = document.getElementById('totalPages');
        const sizeTypes = document.getElementById('sizeTypes');
        const processingTime = document.getElementById('processingTime');
        const sizeStatsTable = document.getElementById('sizeStatsTable');
        const exportCSV = document.getElementById('exportCSV');
        const splitPDF = document.getElementById('splitPDF');
        const splitModal = document.getElementById('splitModal');
        const modalContent = document.getElementById('modalContent');
        const closeModal = document.getElementById('closeModal');
        const cancelSplit = document.getElementById('cancelSplit');
        const confirmSplit = document.getElementById('confirmSplit');
        const splitRanges = document.getElementById('splitRanges');
        const loadingOverlay = document.getElementById('loadingOverlay');
        const loadingText = document.getElementById('loadingText');
        const themeToggle = document.getElementById('themeToggle');
        const helpBtn = document.getElementById('helpBtn');
        const analyzeBtn = document.getElementById('analyzeBtn');

        // 检查pdf-lib库是否加载完成
        function checkPdfLib() {
            try {
                if (typeof PDFLib !== 'undefined' && typeof PDFLib.PDFDocument !== 'undefined') {
                    pdfLibReady = true;
                    console.log('pdf-lib库加载成功');
                } else {
                    pdfLibReady = false;
                    console.warn('pdf-lib库未正确加载');
                }
            } catch (error) {
                pdfLibReady = false;
                console.error('检查pdf-lib库时出错:', error);
            }
        }

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 检查pdf-lib库
            checkPdfLib();
            
            // 拖放事件
            dropZone.addEventListener('dragover', handleDragOver);
            dropZone.addEventListener('dragleave', handleDragLeave);
            dropZone.addEventListener('drop', handleDrop);
            
            // 文件选择事件
            fileInput.addEventListener('change', handleFileSelect);
            
            // 移除文件事件
            removeFile.addEventListener('click', removeSelectedFile);
            
            // 导出CSV事件
            exportCSV.addEventListener('click', exportToCSV);
            
            // 拆分PDF事件
            splitPDF.addEventListener('click', showSplitModal);
            closeModal.addEventListener('click', hideSplitModal);
            cancelSplit.addEventListener('click', hideSplitModal);
            confirmSplit.addEventListener('click', handleSplitPDF);
            
            // 主题切换事件
            themeToggle.addEventListener('click', toggleTheme);
            
            // 帮助按钮事件
            helpBtn.addEventListener('click', showHelp);
            
            // 分析按钮事件
            analyzeBtn.addEventListener('click', function() {
                if (!pdfLibReady) {
                    alert('PDF处理库加载失败，请刷新页面重试');
                    return;
                }
                analyzePDF();
            });
            
            // 按钮点击反馈
            analyzeBtn.addEventListener('click', function() {
                console.log('分析按钮被点击，pdfLibReady:', pdfLibReady);
                this.classList.add('scale-95');
                setTimeout(() => {
                    this.classList.remove('scale-95');
                }, 150);
            });
        });

        // 拖放处理函数
        function handleDragOver(e) {
            e.preventDefault();
            dropZone.classList.add('border-primary', 'bg-blue-50');
        }

        function handleDragLeave(e) {
            e.preventDefault();
            dropZone.classList.remove('border-primary', 'bg-blue-50');
        }

        function handleDrop(e) {
            e.preventDefault();
            dropZone.classList.remove('border-primary', 'bg-blue-50');
            
            if (e.dataTransfer.files.length) {
                handleFiles(e.dataTransfer.files);
            }
        }

        // 文件选择处理函数
        function handleFileSelect(e) {
            if (e.target.files.length) {
                handleFiles(e.target.files);
            }
        }

        // 处理选中的文件
        function handleFiles(files) {
            const file = files[0];
            if (!file.name.endsWith('.pdf')) {
                alert('请选择PDF文件！');
                return;
            }
            
            currentFile = file;
            displayFileInfo();
        }

        // 显示文件信息
        function displayFileInfo() {
            fileName.textContent = currentFile.name;
            fileSize.textContent = formatFileSize(currentFile.size);
            fileInfo.classList.remove('hidden');
            
            // 添加文件上传成功的动画效果
            dropZone.classList.add('border-success');
            dropZone.innerHTML = `
                <span class="text-5xl text-success mb-4">✅</span>
                <p class="text-success font-medium mb-2">文件已上传</p>
                <p class="text-gray-600">点击下方按钮开始分析，或上传新文件</p>
            `;
            
            // 3秒后恢复原样
            setTimeout(() => {
                if (!resultSection.classList.contains('hidden')) return;
                
                dropZone.classList.remove('border-success');
                dropZone.innerHTML = `
                    <span class="text-5xl text-gray-400 mb-4">☁️</span>
                    <p class="text-gray-600 mb-2">拖放PDF文件到这里，或</p>
                    <label class="relative">
                        <span class="inline-block bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-all duration-300 transform hover:scale-105 shadow-md hover:shadow-lg">
                            选择文件
                        </span>
                        <input type="file" id="fileInput" accept=".pdf" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer">
                    </label>
                `;
            }, 3000);
        }

        // 移除选中的文件
        function removeSelectedFile() {
            currentFile = null;
            fileInfo.classList.add('hidden');
            resultSection.classList.add('hidden');
            fileInput.value = '';
            
            // 恢复拖放区域
            dropZone.classList.remove('border-success');
            dropZone.innerHTML = `
                <span class="text-5xl text-gray-400 mb-4">☁️</span>
                <p class="text-gray-600 mb-2">拖放PDF文件到这里，或</p>
                <label class="relative">
                    <span class="inline-block bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-all duration-300 transform hover:scale-105 shadow-md hover:shadow-lg">
                        选择文件
                    </span>
                    <input type="file" id="fileInput" accept=".pdf" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer">
                </label>
            `;
        }

        // 分析PDF文件
        async function analyzePDF() {
            if (!currentFile) {
                alert('请先选择一个PDF文件！');
                return;
            }
            
            if (!pdfLibReady) {
                alert('PDF处理库未加载，请刷新页面重试');
                return;
            }
            
            showLoading('正在分析PDF文件...');
            
            try {
                const startTime = performance.now();
                
                // 读取文件内容
                const arrayBuffer = await readFileAsArrayBuffer(currentFile);
                
                // 使用pdf-lib处理PDF
                const { PDFDocument } = PDFLib;
                const pdfDoc = await PDFDocument.load(arrayBuffer);
                const pageCount = pdfDoc.getPageCount();
                const pageSizeStats = {};
                
                // 分析每一页的尺寸
                for (let i = 0; i < pageCount; i++) {
                    const page = pdfDoc.getPage(i);
                    const { width, height } = page.getSize();
                    const sizeType = getPageSizeType(width, height);
                    
                    if (!pageSizeStats[sizeType]) {
                        pageSizeStats[sizeType] = { count: 0, pages: [] };
                    }
                    pageSizeStats[sizeType].count++;
                    pageSizeStats[sizeType].pages.push(i + 1);
                }
                
                // 为每个尺寸类型添加描述
                for (const sizeType in pageSizeStats) {
                    pageSizeStats[sizeType].description = miaoshu(pageSizeStats[sizeType].pages);
                }
                
                const endTime = performance.now();
                const processTime = ((endTime - startTime) / 1000).toFixed(2);
                
                // 存储统计结果
                pdfStats = {
                    totalPageCount: pageCount,
                    pageSizeStats,
                    processTime
                };
                
                // 显示统计结果
                displayStats();
                
                hideLoading();
                
                // 添加结果出现的动画效果
                resultSection.classList.add('animate-fadeIn');
            } catch (error) {
                hideLoading();
                console.error('PDF分析失败:', error);
                alert(`PDF分析失败，请尝试其他文件\n错误详情: ${error.message}`);
            }
        }

        // 显示统计结果
        function displayStats() {
            if (!pdfStats) return;
            
            // 更新统计数据
            totalPages.textContent = pdfStats.totalPageCount;
            sizeTypes.textContent = Object.keys(pdfStats.pageSizeStats).length;
            processingTime.textContent = `${pdfStats.processTime}s`;
            
            // 清空表格
            sizeStatsTable.innerHTML = '';
            
            // 填充表格
            const sizeEntries = Object.entries(pdfStats.pageSizeStats);
            sizeEntries.sort((a, b) => b[1].count - a[1].count);
            
            sizeEntries.forEach(([sizeType, stats]) => {
                const percentage = ((stats.count / pdfStats.totalPageCount) * 100).toFixed(1);
                const row = document.createElement('tr');
                row.className = 'hover:bg-gray-50 transition-colors';
                
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="flex items-center">
                            <div class="w-4 h-4 rounded-full bg-primary mr-2"></div>
                            <span class="font-medium text-gray-900">${sizeType}</span>
                        </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="text-gray-900">${stats.count}</span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="w-full bg-gray-200 rounded-full h-2.5">
                            <div class="bg-primary h-2.5 rounded-full" style="width: ${percentage}%"></div>
                        </div>
                        <span class="text-sm text-gray-700">${percentage}%</span>
                    </td>
                    <td class="px-6 py-4">
                        <span class="text-gray-900">${stats.description}</span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <button class="text-primary hover:text-primary/80 split-range" data-range="${stats.description}">
                            拆分
                        </button>
                    </td>
                `;
                
                sizeStatsTable.appendChild(row);
            });
            
            // 添加拆分按钮事件
            document.querySelectorAll('.split-range').forEach(btn => {
                btn.addEventListener('click', function() {
                    const range = this.getAttribute('data-range');
                    splitRanges.value = range.replace(/，/g, ',');
                    showSplitModal();
                });
            });
            
            // 显示结果区域
            resultSection.classList.remove('hidden');
            
            // 平滑滚动到结果区域
            setTimeout(() => {
                resultSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }, 300);
        }

        // 导出CSV文件
        function exportToCSV() {
            if (!pdfStats) return;
            
            let csvContent = "页面尺寸,页数,占比,页码范围\n";
            
            const sizeEntries = Object.entries(pdfStats.pageSizeStats);
            sizeEntries.sort((a, b) => b[1].count - a[1].count);
            
            sizeEntries.forEach(([sizeType, stats]) => {
                const percentage = ((stats.count / pdfStats.totalPageCount) * 100).toFixed(1);
                csvContent += `${sizeType},${stats.count},${percentage}%,${stats.description}\n`;
            });
            
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const filename = currentFile.name.replace('.pdf', '_统计.csv');
            saveAs(blob, filename);
        }

        // 显示拆分模态框
        function showSplitModal() {
            splitModal.classList.remove('hidden');
            setTimeout(() => {
                modalContent.classList.remove('scale-95', 'opacity-0');
                modalContent.classList.add('scale-100', 'opacity-100');
            }, 10);
        }

        // 隐藏拆分模态框
        function hideSplitModal() {
            modalContent.classList.remove('scale-100', 'opacity-100');
            modalContent.classList.add('scale-95', 'opacity-0');
            setTimeout(() => {
                splitModal.classList.add('hidden');
            }, 300);
        }

        // 处理PDF拆分
        async function handleSplitPDF() {
            const pageRangeStr = splitRanges.value.trim();
            if (!pageRangeStr) {
                alert('请输入页码范围！');
                return;
            }
            
            hideSplitModal();
            showLoading('正在拆分PDF文件...');
            
            try {
                // 读取文件内容
                const arrayBuffer = await readFileAsArrayBuffer(currentFile);
                
                // 使用pdf-lib处理PDF
                const { PDFDocument } = PDFLib;
                const pdfDoc = await PDFDocument.load(arrayBuffer);
                const pageCount = pdfDoc.getPageCount();
                
                // 解析页码范围
                const pageRanges = parsePageRanges(pageRangeStr);
                
                // 检查页码范围有效性
                const invalidRanges = pageRanges.filter(range => 
                    range.start < 1 || range.end > pageCount || range.start > range.end
                );
                
                if (invalidRanges.length > 0) {
                    hideLoading();
                    alert('页码范围无效，请检查输入！');
                    return;
                }
                
                // 为每个页码范围创建一个新的PDF
                for (let i = 0; i < pageRanges.length; i++) {
                    const range = pageRanges[i];
                    const startPage = range.start - 1; // 页码从1开始，索引从0开始
                    const endPage = range.end - 1;
                    
                    // 创建一个新的PDF文档
                    const newPdfDoc = await PDFDocument.create();
                    
                    // 将指定范围的页面复制到新文档
                    for (let j = startPage; j <= endPage; j++) {
                        const [copiedPage] = await newPdfDoc.copyPages(pdfDoc, [j]);
                        newPdfDoc.addPage(copiedPage);
                    }
                    
                    // 保存新文档
                    const newPdfBytes = await newPdfDoc.save();
                    const blob = new Blob([newPdfBytes], { type: 'application/pdf' });
                    const filename = `${currentFile.name.replace('.pdf', '')}_${range.start}-${range.end}.pdf`;
                    
                    // 延迟下载，避免浏览器阻止多个下载
                    if (i === pageRanges.length - 1) {
                        // 最后一个文件直接下载
                        saveAs(blob, filename);
                    } else {
                        // 其他文件使用setTimeout延迟下载
                        setTimeout(() => {
                            saveAs(blob, filename);
                        }, 1000 * i);
                    }
                }
                
                hideLoading();
                alert(`PDF已成功拆分为${pageRanges.length}个文件！`);
            } catch (error) {
                hideLoading();
                console.error('PDF拆分失败:', error);
                alert(`PDF拆分失败，请重试\n错误详情: ${error.message}`);
            }
        }

        // 显示加载动画
        function showLoading(text = '处理中...') {
            loadingText.textContent = text;
            loadingOverlay.classList.remove('hidden');
        }

        // 隐藏加载动画
        function hideLoading() {
            loadingOverlay.classList.add('hidden');
        }

        // 切换主题
        function toggleTheme() {
            const body = document.body;
            if (body.classList.contains('dark')) {
                body.classList.remove('dark');
                themeToggle.innerHTML = '<span class="text-gray-600">🌙</span>';
            } else {
                body.classList.add('dark');
                themeToggle.innerHTML = '<span class="text-yellow-400">☀️</span>';
            }
        }

        // 显示帮助信息
        function showHelp() {
            alert('PDF页面信息统计工具帮助：\n\n1. 上传PDF文件：通过拖放或点击"选择文件"按钮上传PDF文件\n2. 开始分析：点击"开始分析"按钮分析PDF的页面尺寸、页数等信息\n3. 查看结果：分析完成后将显示统计结果表格\n4. 导出CSV：将统计结果导出为CSV文件\n5. 按尺寸拆分：根据页面尺寸或自定义页码范围拆分PDF文件');
        }

        // 工具函数：读取文件为ArrayBuffer
        function readFileAsArrayBuffer(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = () => resolve(reader.result);
                reader.onerror = reject;
                reader.readAsArrayBuffer(file);
            });
        }

        // 工具函数：格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
    </script>
</body>
</html>